<template>
  <div class="dog-camera-container">
    <!-- 头部控制栏 -->
    <div class="camera-header">
      <div class="header-left">
        <el-icon class="camera-icon"><VideoCamera /></el-icon>
        <span class="camera-title">机器狗视角</span>
      </div>
      
      <div class="header-controls">
        <button class="control-btn" @click="toggleFullscreen">
          <el-icon><FullScreen /></el-icon>
        </button>
        <button class="control-btn" @click="takeScreenshot">
          <el-icon><Camera /></el-icon>
        </button>
      </div>
    </div>
    
    <!-- 视频显示区域 -->
    <div class="video-container" ref="videoContainer">
      <video 
        ref="videoElement"
        class="camera-feed"
        autoplay
        muted
        playsinline
        @loadedmetadata="handleVideoLoaded"
        @error="handleVideoError"
      ></video>
      
      <!-- 连接状态指示器 -->
      <div v-if="!isConnected && !isConnecting" class="connection-status error">
        <el-icon><Warning /></el-icon>
        <span>视频流未连接</span>
      </div>
      
      <div v-if="isConnecting" class="connection-status connecting">
        <el-icon class="loading-icon"><Loading /></el-icon>
        <span>正在连接...</span>
      </div>
      
      <!-- 视频叠加信息 -->
      <div class="video-overlay" v-if="isConnected">
        <div class="video-info">
          <span class="resolution">{{ videoResolution }} • {{ videoFps }}FPS</span>
        </div>
        <div class="live-indicator">
          <span class="live-dot"></span>
          <span class="live-text">实时</span>
        </div>
      </div>
      
      <!-- 录制状态指示器 -->
      <div v-if="isRecording" class="recording-indicator">
        <el-icon class="recording-icon"><VideoPlay /></el-icon>
        <span>录制中</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { VideoCamera, FullScreen, Camera, VideoPlay, Warning, Loading } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { loadSceneConfig, getCameraConfig } from '@/utils/configLoader'

const videoContainer = ref(null)
const videoElement = ref(null)
const isRecording = ref(false)
const isConnected = ref(false)
const isConnecting = ref(false)
const videoResolution = ref('1080p')
const videoFps = ref('30')

// 配置相关
const cameraConfig = ref(null)
const whepUrl = ref('')

// WebRTC 相关
const peerConnection = ref(null)

// 初始化配置
const initializeConfig = () => {
  try {
    // 配置已经在 main.js 中预加载，直接获取
    cameraConfig.value = getCameraConfig('dogCamera')
    
    if (cameraConfig.value?.whepUrl) {
      whepUrl.value = cameraConfig.value.whepUrl
      console.log('机器狗摄像头配置:', cameraConfig.value)
      return true
    } else {
      throw new Error('未找到机器狗摄像头配置')
    }
  } catch (error) {
    console.error('配置初始化失败:', error)
    ElMessage.error('摄像头配置加载失败')
    return false
  }
}

// WebRTC 连接函数
const connectWebRTC = async () => {
  if (isConnecting.value || isConnected.value) return
  
  if (!whepUrl.value) {
    ElMessage.error('摄像头配置未加载，无法连接')
    return
  }
  
  try {
    isConnecting.value = true
    console.log('开始连接 WebRTC 视频流...', whepUrl.value)
    
    // 创建 RTCPeerConnection
    peerConnection.value = new RTCPeerConnection({
      iceServers: [
        { urls: 'stun:stun.l.google.com:19302' },
        { urls: 'stun:stun1.l.google.com:19302' }
      ]
    })

    // 处理接收到的媒体流
    peerConnection.value.ontrack = (event) => {
      console.log('接收到媒体流')
      if (videoElement.value && event.streams[0]) {
        videoElement.value.srcObject = event.streams[0]
        isConnected.value = true
        isConnecting.value = false
        ElMessage.success('视频流连接成功')
      }
    }

    // 处理连接状态变化
    peerConnection.value.onconnectionstatechange = () => {
      const state = peerConnection.value?.connectionState
      console.log('连接状态:', state)
      
      if (state === 'connected') {
        isConnected.value = true
        isConnecting.value = false
      } else if (state === 'disconnected' || state === 'failed') {
        isConnected.value = false
        isConnecting.value = false
        ElMessage.error('视频流连接断开')
      }
    }

    // 处理 ICE 连接状态
    peerConnection.value.oniceconnectionstatechange = () => {
      const state = peerConnection.value?.iceConnectionState
      console.log('ICE 连接状态:', state)
    }

    // 创建 offer
    const offer = await peerConnection.value.createOffer({
      offerToReceiveVideo: true,
      offerToReceiveAudio: true
    })
    
    await peerConnection.value.setLocalDescription(offer)

    // 发送 WHEP 请求
    const response = await fetch(whepUrl.value, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/sdp'
      },
      body: offer.sdp
    })

    if (!response.ok) {
      throw new Error(`WHEP 请求失败: ${response.status} ${response.statusText}`)
    }

    const answerSdp = await response.text()
    
    // 设置远程描述
    await peerConnection.value.setRemoteDescription(new RTCSessionDescription({
      type: 'answer',
      sdp: answerSdp
    }))

    console.log('WebRTC 连接建立成功')
    
  } catch (error) {
    console.error('WebRTC 连接失败:', error)
    isConnecting.value = false
    isConnected.value = false
    ElMessage.error(`连接失败: ${error.message}`)
  }
}

// 断开 WebRTC 连接
const disconnectWebRTC = () => {
  if (peerConnection.value) {
    peerConnection.value.close()
    peerConnection.value = null
  }
  
  if (videoElement.value) {
    videoElement.value.srcObject = null
  }
  
  isConnected.value = false
  isConnecting.value = false
  console.log('WebRTC 连接已断开')
}

// 重新连接
const reconnectWebRTC = async () => {
  disconnectWebRTC()
  await new Promise(resolve => setTimeout(resolve, 1000)) // 等待1秒
  await connectWebRTC()
}

const toggleFullscreen = () => {
  if (document.fullscreenElement) {
    document.exitFullscreen()
  } else {
    videoContainer.value?.requestFullscreen()
  }
}

const takeScreenshot = () => {
  if (!videoElement.value || !isConnected.value) {
    ElMessage.warning('请先连接视频流')
    return
  }
  
  try {
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    
    canvas.width = videoElement.value.videoWidth
    canvas.height = videoElement.value.videoHeight
    
    ctx.drawImage(videoElement.value, 0, 0)
    
    // 下载截图
    const link = document.createElement('a')
    link.download = `screenshot_${new Date().getTime()}.png`
    link.href = canvas.toDataURL()
    link.click()
    
    ElMessage.success('截图已保存')
  } catch (error) {
    console.error('截图失败:', error)
    ElMessage.error('截图失败')
  }
}

const handleVideoLoaded = () => {
  console.log('视频加载完成')
  if (videoElement.value) {
    videoResolution.value = `${videoElement.value.videoWidth}x${videoElement.value.videoHeight}`
  }
}

const handleVideoError = (error) => {
  console.error('视频播放错误:', error)
  ElMessage.error('视频播放失败')
}

const startRecording = () => {
  if (!isConnected.value) {
    ElMessage.warning('请先连接视频流')
    return
  }
  
  isRecording.value = true
  ElMessage.success('开始录制')
  // TODO: 实现录制逻辑
}

const stopRecording = () => {
  isRecording.value = false
  ElMessage.success('录制已停止')
  // TODO: 实现停止录制逻辑
}

onMounted(async () => {
  const configLoaded = initializeConfig()
  if (configLoaded) {
    await connectWebRTC()
  }
})

onUnmounted(() => {
  disconnectWebRTC()
})

// 暴露方法供父组件调用
defineExpose({
  connectWebRTC,
  disconnectWebRTC,
  reconnectWebRTC,
  takeScreenshot,
  startRecording,
  stopRecording,
  initializeConfig,
  cameraConfig
})
</script>

<style scoped>
.dog-camera-container {
  background: rgba(10, 25, 47, 0.9);
  backdrop-filter: blur(8px);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  box-shadow: 0px 4px 12px 0px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

.camera-header {
  background: var(--secondary-bg);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 8px;
  height: 28px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 4px;
}

.camera-icon {
  color: var(--primary-blue);
  font-size: 14px;
}

.camera-title {
  color: var(--text-primary);
  font-size: 13px;
  font-weight: 500;
  line-height: 1;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 4px;
}

.control-btn {
  background: none;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  padding: 2px;
  border-radius: 4px;
  transition: color 0.3s ease;
  font-size: 12px;
}

.control-btn:hover {
  color: var(--primary-blue);
}

.video-container {
  position: relative;
  width: 278px;
  height: 350px;
  background: linear-gradient(0deg, #0F2748 0%, #0F2748 100%), #000000;
  overflow: hidden;
}

.camera-feed {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  background: #000;
}

.video-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  padding: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.video-info {
  display: flex;
  align-items: center;
}

.resolution {
  color: var(--text-secondary);
  font-size: 12px;
}

.live-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
}

.live-dot {
  width: 8px;
  height: 8px;
  background: #EF4444;
  border-radius: 50%;
  animation: blink 1s infinite;
}

.live-text {
  color: var(--text-secondary);
  font-size: 12px;
}

.recording-indicator {
  position: absolute;
  top: 8px;
  right: 8px;
  background: rgba(239, 68, 68, 0.9);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
}

.recording-icon {
  font-size: 14px;
  animation: blink 1s infinite;
}

.connection-status {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  z-index: 10;
}

.connection-status.error {
  background: rgba(239, 68, 68, 0.9);
  color: white;
}

.connection-status.connecting {
  background: rgba(59, 130, 246, 0.9);
  color: white;
}

.loading-icon {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@keyframes blink {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0.3;
  }
}
</style>